package com.flashcash.kotlin.activity

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.text.TextUtils
import com.facebook.accountkit.AccountKitError
import com.facebook.accountkit.AccountKitLoginResult
import com.flashcash.kotlin.auth.accountKit.AccountKitLoginManager
import com.flashcash.kotlin.auth.accountKit.LoginEventBus
import com.flashcash.kotlin.widget.LocalButton
import com.flashcash.solu.R
import com.flashcash.solu.app.base.BaseActivity
import com.flashcash.solu.app.base.BaseActivityView
import com.flashcash.solu.app.base.presenter.BaseActivityPresenter
import com.flashcash.solu.app.base.presenter.BaseActivityPresenterImpl
import com.flashcash.solu.bean.LoginTokenResponse
import com.flashcash.solu.common.EventCollection
import com.flashcash.solu.common.TokenManager
import com.flashcash.solu.common.network.HttpErrorHandledSubScriber
import com.flashcash.solu.common.network.ServiceGenerator
import com.flashcash.solu.common.network.UserApi
import com.flashcash.solu.view.login.LoginActivity
import com.hwangjr.rxbus.RxBus
import com.kredit.kotlin.firebase.FirebaseUtil
import com.x.leo.apphelper.log.XLog
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk25.coroutines.onClick
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

/**
 * Created by XLEO on 2018/3/6.
 */
class LoginSwitcher : BaseActivity<LoginSwitcherPresenter>(), LoginSwitcherView {
    override fun onError(e: Throwable?) {
        AlertDialog.Builder(this)
                .setTitle(R.string.tips_title)
                .setMessage(e?.message ?: getString(R.string.error_occured))
                .setPositiveButton(R.string.button_ok, { dialog, _ ->
                    dialog.dismiss()
                    switch()
                })
                .create()
                .show()
    }

    // LoginSwitcher ends in 2 state:
    // 1. success: i. facebook account kit login success (here) ii. LoginActivity success (onActivityResult)
    // 2. cancel
    override fun onSuccess() {
        // facebook account kit login success
        RxBus.get().post(EventCollection.LoginSuccess())
        LoginEventBus.postSuccess()
        reset()
        finish()
    }

    override fun onBackPressed() {
        LoginEventBus.postCancel()
        super.onBackPressed()
    }

    companion object {
        val LOGIN_FACEBOOK_ACCOUNT_KIT = 0x1f23
        val LOGIN_ACTIVITY_REQUEST_CODE = 0x1f25
    }

    override fun getLayoutResId(): Int = R.layout.activity_login_switcher

    private var doRequestPermission: Boolean = false

    override fun init() {
        find<LocalButton>(R.id.btn_facebook_login).onClick {
            loginByAccountKit()
        }
        find<LocalButton>(R.id.btn_normal_login).onClick {
            loginByNormal()
        }
        doRequestPermission = true
    }

    private fun switch() {
        find<LocalButton>(R.id.btn_facebook_login).apply {
            scaleX = 0.5f
            scaleY = 0.5f
        }
        find<LocalButton>(R.id.btn_normal_login).apply {
            scaleX = 1f
            scaleY = 1f
        }

    }

    private fun reset() {
        find<LocalButton>(R.id.btn_normal_login).apply {
            scaleX = 0.5f
            scaleY = 0.5f
        }
        find<LocalButton>(R.id.btn_facebook_login).apply {
            scaleX = 1f
            scaleY = 1f
        }
    }

    override fun onStart() {
        super.onStart()
        if (doRequestPermission) {
            requestPermission()
        }
    }

    private fun requestPermission() {
//        try {
//            TraceManager.uploadInfo(this, Manifest.permission.READ_PHONE_STATE)
//            TraceManager.uploadInfo(this, Manifest.permission.READ_SMS)
//            TraceManager.uploadInfo(this, Manifest.permission.ACCESS_COARSE_LOCATION)
//            //addSmsObserver();
//        } catch (e: Exception) {
//            XLog.d("Exception: " + e.message, 10)
//        }
    }

    private fun loginByNormal() {
        startActivityForResult(Intent(this, LoginActivity::class.java), LOGIN_ACTIVITY_REQUEST_CODE)
    }

    private fun loginByAccountKit() {
        AccountKitLoginManager.callBack = object : AccountKitLoginManager.CallBack {
            override fun onError(error: AccountKitError?) {
                AccountKitLoginManager.callBack = null
                XLog.i("error:" + error?.toString(), 10)
                switch()
            }

            override fun onSuccess(loginResult: AccountKitLoginResult) {


                AccountKitLoginManager.callBack = null
                XLog.i(loginResult.authorizationCode ?: "null", 10)
                mPresenter.loginByAccountKit(loginResult.authorizationCode!!)
                if (!TextUtils.isEmpty(FirebaseUtil.getFirebaseToken(context))) {
                    FirebaseUtil.uploadFirebaseTokenWithRetry(FirebaseUtil.getFirebaseToken(context)!!)
                }
            }

            override fun onCancel(loginResult: AccountKitLoginResult) {
                AccountKitLoginManager.callBack = null
                XLog.i("cancel", 10)
                switch()
            }
        }
        startActivityForResult(AccountKitLoginManager.phoneLogin(this), LOGIN_FACEBOOK_ACCOUNT_KIT)
    }

    override fun initPresenterImpl(): LoginSwitcherPresenter {
        return LoginSwitcherPreImpl()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == LOGIN_FACEBOOK_ACCOUNT_KIT && data != null) {
            AccountKitLoginManager.handleResult(data, this)
        } else if (requestCode == LOGIN_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            LoginEventBus.postSuccess()
            finish()
        }
    }

}

class LoginSwitcherPreImpl : LoginSwitcherPresenter, BaseActivityPresenterImpl() {
    override fun loginByAccountKit(authorizationCode: String) {
        showLoading("")
        ServiceGenerator.createService(UserApi::class.java)
                .login_new(null, authorizationCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : HttpErrorHandledSubScriber<LoginTokenResponse>() {
                    override fun onFinalError(e: Throwable?) {
                        dismissLoading()
                        if (isAttached) {
                            (mView as LoginSwitcherView).onError(e)
                        }
                    }

                    override fun onNext(p0: LoginTokenResponse?) {
                        XLog.i("" + p0?.token, 10)
                        if (p0?.token != null) {
                            TokenManager.getInstance().setToken(p0.token, 0)
                            TokenManager.getInstance().mobile = "800000000"
                            RxBus.get().post(EventCollection.AccoutUpdateEvent())
                            dismissLoading()
                            (mView as LoginSwitcherView).onSuccess()
                        }


                    }
                })
    }

}

interface LoginSwitcherPresenter : BaseActivityPresenter {
//    fun loginByAccountKit(authorizationCode: String)

}

interface LoginSwitcherView : BaseActivityView {
    fun onError(e: Throwable?)
    fun onSuccess()

}
